<!DOCTYPE>
<html>
<head>
  <meta charset="utf-8">
  <title>ChatMiMaBuShiAdmin</title>
  <link rel="stylesheet" type="text/css" href="css/layout.css">
  <script src="http://lib.sinaapp.com/js/jquery/1.5.2/jquery.min.js"></script>
<script>
$(function(){
    if (navigator.userAgent.indexOf('Chrome') == -1 || !WebSocket){
        console.log('11111');
        return;
    }
    var validateIp = function(ip){
        return (/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.test(ip) && (RegExp.$1 <256 && RegExp.$2<256 && RegExp.$3<256 && RegExp.$4<256));
    };
    var addMsg = function(message){
        if($('#lockNewMsg').attr('checked'))
            return;
        var row = $("<div></div>").addClass("chat-msg");
        
        var time = '*';
        try{
            time = formatTime(message.timestamp);
        }catch(e){}
        $("<span></span>")
            .addClass("chat-time")
            .text(time)
            .appendTo(row);
        
        var nick = '*';
        try{
            nick = decodeURIComponent(message.nick);
        }catch(e){}
        $("<span></span>")
            .addClass("chat-nick")
            .text(nick)
            .appendTo(row);
            
        var text = 'Unknow';  
        try{
            text = decodeURIComponent(message.text) + '<' + message.ip + '>';
        }catch(e){}
        $("<span></span>")
            .addClass("chat-text")
            .text(text)
            .appendTo(row);
            
        $("#chat-log").prepend(row);
        while($('.chat-msg:last').position() && $('.chat-msg:last').position().top > $('#chat-log').height()) {
            $('.chat-msg:last').remove();
        }
    };
    var admin_param = ['sysMessage', 'addIpBlock_Send', 'addIpBlock_Recv', 'addIpBlock_Join', 'removeIpBlock_Send', 'removeIpBlock_Recv', 'removeIpBlock_Join', 'getIpBlock'];
    var chat_form_select = $('<select>').attr('id','chat_form_select');
    for (var i = 0;i < admin_param.length;i++){
        chat_form_select.append($('<option>').attr('value', admin_param[i]).text(admin_param[i])).attr('id','chat_form' + admin_param[i]);
    }
    
    var smiles = [
            ['http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/1b/gz_thumb.gif'],
            ['http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/c9/geili_thumb.gif']
        ];
    
    $('#chat-form').append(chat_form_select).append($('<input>').attr('size',15).attr('id','chat_form_input').val('Connectting..').attr('disabled','true').css('width','320'))
    .append($('<input>').attr('type','submit').attr('value','Set').css('width','6em'))
    .append(
        $('<label>').append(
            $('<span>').text('LOCK')
        ).append($('<input>').attr('id','lockNewMsg').attr('type','checkbox').css('width','auto'))
    ).append($('<a>').text('img').css('padding','0 5px').attr('href','javascript:voide(0)').click(function(){
        var sr = prompt('image url');
        $('#chat_form_input').val('<img src=\"' + sr + '\"/>');
    }))
    .append($('<span>').attr('id','sysInfo').css('padding-right','5px'));
    
    for (var i = 0;i < smiles.length; i++){
        $('#chat-form').append($('<img>').attr('src',smiles[i]).click(function(){
            $('#chat_form_input').val('<img src=\"' + $(this).attr('src') + '\"/>');
        }).css('cursor','hand'));
    }
    $('#chat-form').submit(function() {
        var method = '', type = '';
        method = $('#chat-form select option:selected').attr('value');
        switch($('#chat-form select option:selected').attr('value')){
            case 'addIpBlock_Send':
            case 'addIpBlock_Recv':
            case 'addIpBlock_Join':
            case 'removeIpBlock_Send':
            case 'removeIpBlock_Recv':
            case 'removeIpBlock_Join':
                method = method.split('_');
                type = method[1].toLocaleLowerCase();
                var ip = $.trim($('#chat_form_input').val());
                if (!ip || !validateIp(ip)){
                    alert('illegal ip');
                    return false;
                }
                connect.send({target:method[0],ip:ip,type:type}, function(a,b){
                    addMsg({
                        text:'Result:' + (a.status?'Accept':'PE')
                    });
                });
            break;
            
            case 'sysMessage':
                connect.send({target:'sysMessage',text:$('#chat_form_input').val()});
            break;
            
            case 'getIpBlock':
                connect.send({target:'getIpBlock'}, function(a, b){
                    console.log('ips list',a);
                });
            break;
            default:
                break;
                
        }
    	return false;
	})
    connect = (function(){
        var id = 1;
        //var _ws = new WebSocket("ws://example.cnodejs.net:10086");
        var _ws = new WebSocket('ws://' + location.hostname + ':10086');
        _ws.connQueue = {};
        _ws.onerror = _ws.onclose = function(e){
            console.log('WS',e);
            $('#chat_form_input').val('lose connection.reload ?').attr('disabled','true');
        };
        _ws.onopen = function(){
            var v = {
                target: 'login'
            };
            console.log('WS OPEN');
            v.name = prompt('name');
            v.key = prompt('key');
            that.send(v, function(){
                console.log('success');
                $('#chat_form_input').removeAttr('disabled').val('');
                _ws._ping = setInterval(function(){
                    that.send({
                        target: 'ping'
                    });
                }, 2000);
            });
        };
        _ws.onmessage = function(event){
            try{
                var data = JSON.parse(event.data);
                if (typeof data._msgId != 'undefined' && typeof this.connQueue[data._msgId] != 'undefined' && typeof this.connQueue[data._msgId].callback == 'function')
                        this.connQueue[data._msgId].callback(data,this.connQueue[data._msgId].sent);
                switch(data.target){
                    case 'newMessage':
                        addMsg(data.data);
                    break;
                    case 'sysInfo':
                        $('#sysInfo').text('Mem:' + Math.floor(data.data.mem) + 'M,Online:' + data.data.online + ',PeakOnline:' + data.data.maxOnline);
                        //console.log(data.data);
                    break;
                }
            }
            catch(e){
                console.log('error', e, event);
            }
        }
        var that = {
            send: function(request, callback){
                id ++;
                request._msgId = id;
                try{
                    if (typeof callback == 'function'){
                        _ws.connQueue[request._msgId] = {
                            'sent': request,
                            'callback': callback
                        };
                    }
                    _ws.send(JSON.stringify(request));    
                }catch(e){
                    alert(e.message);
                }
                
            }
        };
        return that;
    })();
    
});
function formatTime(timestamp) {
        var date = new Date(timestamp),
            hours = date.getHours(),
            minutes = date.getMinutes(),
            ampm = "AM";
        if (hours > 12) {
            hours -= 12;
            ampm = "PM";
        }
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        return hours + ":" + minutes + " " + ampm;
    }
</script>
</head>
<body>
<form id="chat-form">
    </form>
    <div id="chat-log">
        
    </div>
    <div id="footer">
        <a href="javascript:void(0);" id="myId">0_0</a>
    </div>
</body>
</html>